public class NumberToWords {
  private static final String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
  private static final String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
  private static final String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
  private static final String[] thousands = {"", "Thousand", "Million", "Billion"};

  public String numberToWords(int num) {
      if (num == 0) {
          return "Zero";
      }
      
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < thousands.length; i++) {
          if (num % 1000 != 0) {
              String part = smallNumberToWords(num % 1000);
              if (i > 0) {
                  part += " " + thousands[i];
              }
              if (sb.length() > 0) {
                  sb.insert(0, part + " ");
              } else {
                  sb.append(part);
              }
          }
          num /= 1000;
          if (num == 0) break;
      }
      
      return sb.toString().trim();
  }

  private String smallNumberToWords(int num) {
      if (num == 0) {
          return "";  // 返回空字符串而不是"zero"
      }
      
      StringBuilder sb = new StringBuilder();
      
      if (num >= 100) {
          sb.append(ones[num / 100]).append(" Hundred");
          num %= 100;
          if (num > 0) {
              sb.append(" ");
          }
      }
      
      if (num > 0) {
          if (num < 10) {
              sb.append(ones[num]);
          } else if (num < 20) {
              sb.append(teens[num - 10]);
          } else {
              sb.append(tens[num / 10]);
              num %= 10;
              if (num > 0) {
                  sb.append(" " + ones[num]);
              }
          }
      }
      
      return sb.toString();
  }
  public static void main(String[] args) {
    NumberToWords n = new NumberToWords();
    System.out.println(n.numberToWords(123));
  }
}


// 示例 1：

// 输入：123
// 输出："One Hundred Twenty Three"
// 示例 2：

// 输入：12345
// 输出："Twelve Thousand Three Hundred Forty Five"
// 示例 3：

// 输入：1234567
// 输出："One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
// 示例 4：

// 输入：1234567891
// 输出："One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
